package com.sl.au.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.Chance;
import com.sl.au.entity.ContractInfoQuoteDevice;
import com.sl.au.entity.ExpectedOrder;
import com.sl.au.entity.ExpectedOrderAnalysis;
import com.sl.au.entity.ExpectedOrderToChance;
import com.sl.au.entity.Module;
import com.sl.au.entity.Option;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.User;
import com.sl.au.service.ChanceService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.ExpectedOrderService;
import com.sl.au.service.ExpectedOrderToChanceService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;

@RestController
@RequestMapping(value = "/ui/expectedOrder")
public class ExpectedOrderController extends BaseController {
	
	@Autowired
	private ExpectedOrderService expectedOrderService;
	
	@Autowired
	private ExpectedOrderToChanceService expectedOrderToChanceService;
	
	@Autowired
	SaleAreaService saleAreaService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	OperateLogService operateLogService;
	
	@Autowired
	ChanceService chanceService;
	
	@Autowired
	ExcelService excelService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("expectedOrder/expectedOrderindex");
		Module module = this.getPageModule("ExpectedOrder");
		String unitGroup = "单位";
		Account a = this.getMyAccount();
		List<SaleArea> peosaleAreas = saleAreaService.getRepository().findBySuperior(a.getUser().getSaleArea().getSuperior());
		List<Option> orderUnits = optionService.getRepository().findByGroup(unitGroup);
		modelAndView.addObject("peosaleAreas", peosaleAreas);
		modelAndView.addObject("orderUnits", orderUnits);
		modelAndView.addObject("module", module);
		return modelAndView;
	}
	
	/**
	 * 新增预计订单界面
	 * @return
	 */
	@RequestMapping(value="/register",method = RequestMethod.GET)
	public ModelAndView register() {
		ModelAndView modelAndView = this.createLayoutView("expectedOrder/expectedOrderRegister");
		String unitGroup = "单位";
		Account a = this.getMyAccount();
		String userName=a.getUser().getName();
		String userId=a.getUser().getId();
		String userSuperior=a.getUser().getSaleArea().getSuperior();
		String userSuperiorArea=a.getUser().getSaleArea().getSuperiorArea();
		List<SaleArea> saleAreas = saleAreaService.getRepository().getAllSaleArea();
		List<SaleArea> peosaleAreas = saleAreaService.getRepository().findBySuperior(a.getUser().getSaleArea().getSuperior());
		List<Option> orderUnits = optionService.getRepository().findByGroup(unitGroup);
		modelAndView.addObject("orderUnits", orderUnits);
		modelAndView.addObject("userName", userName);
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("userSuperior", userSuperior);
		modelAndView.addObject("saleAreas", saleAreas);
		modelAndView.addObject("peosaleAreas", peosaleAreas);
		modelAndView.addObject("userSuperiorArea", userSuperiorArea);
		return modelAndView;
	}
	
	
	
	/**
	 * 获取预计订单页面数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getpage", method = RequestMethod.GET)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,String> condition = new HashMap<String,String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if(key == null){key ="";}
		//权限控制
		Module module = this.getPageModule("ExpectedOrder");
		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String area = a.getUser().getSaleArea().getAreaName();
		
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		condition.put("superior", superior);
		condition.put("area", area);
		condition.put("userId", userId);
		
		List<ExpectedOrderToChance> expectedOrders = expectedOrderToChanceService.getExpectedOrder(start, length, condition, null, null);
		
		long count = expectedOrderToChanceService.getExpectedOrderCount(condition);
		map.put("data", expectedOrders);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 获取机会页面数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getpageChance", method = RequestMethod.GET)
	public Map<String,Object> getPageChance(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,String> condition = new HashMap<String,String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
//		String state = request.getParameter("state");
		String state = "已提交";
		if(key == null){key ="";}
		Account a = this.getMyAccount();
		String userId=a.getUser().getId();
		condition.put("key", key);
		condition.put("state", state);
		condition.put("userId", userId);
		List<Chance> saleChances = chanceService.getSaleChances(start, length, condition, "createTime", "desc");
		int count = chanceService.getSaleChanceCount(condition);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	
	/**
	 * 保存预计订单信息
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/save2chance", method = RequestMethod.POST)
	public Map<String, Object> saveExpectedOrder2Chance(HttpServletRequest request, @RequestBody Map<String,Object> jsonmap) throws ParseException {
		
		Map<String, Object> map = new HashMap<String, Object>();
	
		String chanceId = (String) jsonmap.get("chanceId");
		String orderUnitArea = (String) jsonmap.get("orderUnitArea");
		String orderUnit = (String) jsonmap.get("orderUnit");
		String name = (String) jsonmap.get("name");
		String deviceState = (String) jsonmap.get("deviceState");
		Chance chance = chanceService.getRepository().findOne(chanceId);
		chance.setName(name);
		chance.setOrderUnitArea(orderUnitArea);
		chance.setOrderUnit(orderUnit);
		chance.setDeviceState(deviceState);
		chanceService.getRepository().save(chance);
		
		String chargePerson = (String) jsonmap.get("chargePerson");
		double probability = Double.parseDouble((String) jsonmap.get("probability"));
		Integer orderAmount = Integer.valueOf((String) jsonmap.get("orderAmount"));
		long amountMoney = Long.valueOf((String) jsonmap.get("amountMoney"));
		String explain = (String) jsonmap.get("explain");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String date = (String) jsonmap.get("expectedDate");
		Date expectedDate = formatter.parse(date);
		User user = this.getMyAccount().getUser();
		
		if(!jsonmap.containsKey("orderId")) {//新增预计订单
			ExpectedOrder expectedOrder = new ExpectedOrder();
			expectedOrder.setChance(chance);
			expectedOrder.setUser(user);
			expectedOrder.setChargePerson(chargePerson);
			expectedOrder.setProbability(probability);
			expectedOrder.setOrderAmount(orderAmount);
			expectedOrder.setAmountMoney(amountMoney);
			expectedOrder.setExplain(explain);
			expectedOrder.setExpectedDate(expectedDate);
			expectedOrderService.getRepository().save(expectedOrder);
		}else {
			String orderId = (String) jsonmap.get("orderId");
			ExpectedOrder expectedOrder = expectedOrderService.getRepository().findOne(orderId);
			expectedOrder.setChance(chance);
			expectedOrder.setUser(user);
			expectedOrder.setChargePerson(chargePerson);
			expectedOrder.setProbability(probability);
			expectedOrder.setOrderAmount(orderAmount);
			expectedOrder.setAmountMoney(amountMoney);
			expectedOrder.setExplain(explain);
			expectedOrder.setExpectedDate(expectedDate);
			expectedOrderService.getRepository().save(expectedOrder);
		}
		
		//保存日志
		
//		Account a = this.getMyAccount();
//		User user=a.getUser();
//		String Name=expectedOrder.getName();
//		String content = "新增预计订单信息【"+Name+"】";
//		operateLogService.log(user, "预计订单", content);
		map.put("code", 0);
		return map;
	}
	
	/**
	 * 机会登记表编辑页面
	 * 获取机会信息
	 * @return
	 */
	@RequestMapping(value = "/getChance/{chanceId}",method = RequestMethod.POST)
	public Map<String, Object>  getChance(@PathVariable("chanceId") String chanceId) {
		Chance chance = chanceService.getRepository().findOne(chanceId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("chance", chance);
		map.put("code", 0);
		return map;
	}
	

	/**
	 * 预计订单编辑获取数据
	 * 获取机会信息
	 * @return
	 */
	@RequestMapping(value = "/getOrder/{orderId}",method = RequestMethod.POST)
	public Map<String, Object>  getOrder(@PathVariable("orderId") String orderId ){
		Map<String, Object> map = new HashMap<String, Object>();
		ExpectedOrder expectedOrder = expectedOrderService.getRepository().findOne(orderId);
		String userId=this.getMyAccount().getUser().getId();
		if(userId.equals(expectedOrder.getUser().getId())) {
			map.put("order", expectedOrder);
			map.put("code", 0);
		}else {
			map.put("code", 1);
			map.put("msg", "只能修改属于自己的预计订单信息!");
		}
		
		return map;
	}
	
	
	/**
	 * 保存预计订单信息
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
	public Map<String, Object> deleteExpectedOrder( @RequestBody Map<String,Object> jsonmap) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId=this.getMyAccount().getUser().getId();
		List<String> delIds = (List<String>) jsonmap.get("delIds");
        if(expectedOrderService.deleteExpectedOrderCount(delIds, userId)) {
        		map.put("code", 1);
			map.put("msg", "只能删除属于自己的预计订单信息!");
        }else {
        		map.put("code", 0);
        		map.put("msg", "删除成功!");
        }
        
		return map;
	}
	
	/**
	 * 导出预计订货细目
	 * @param
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/export", method = RequestMethod.GET)
	public ResponseEntity<org.springframework.core.io.Resource> excelFile()throws UnsupportedEncodingException {
		Map<String, String> condition = new HashMap<String, String>();
		String begin = request.getParameter("begin");
		String end = request.getParameter("end");
		//权限控制
		Module module = this.getPageModule("ExpectedOrder");
		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String area = a.getUser().getSaleArea().getAreaName();
		
		condition.put("dataFilter", dataFilter);
		condition.put("superior", superior);
		condition.put("area", area);
		condition.put("userId", userId);
		
		condition.put("begin", begin);
		condition.put("end", end);
		List<ExpectedOrder> orders =  expectedOrderService.getExpectedOrderByTime(0, 100000, condition, null, null);
		return this.excelService.toExcel(orders, "预计订货细目.xlsx");
	}
	
	/**
	 * 导出预计订货分析报表
	 * @param
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/exportAnalysis", method = RequestMethod.GET)
	public ResponseEntity<org.springframework.core.io.Resource> excelAnalysisFile() throws UnsupportedEncodingException {
		Map<String, String> condition = new HashMap<String, String>();
		String month = request.getParameter("month");
		//权限控制
		Module module = this.getPageModule("ExpectedOrder");
		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String area = a.getUser().getSaleArea().getAreaName();
		condition.put("dataFilter", dataFilter);
		condition.put("superior", superior);
		condition.put("area", area);
		condition.put("userId", userId);
		condition.put("month", month);
		
		List<ExpectedOrderAnalysis> analysis =  expectedOrderService.getExpectedOrderForAnalysis(0, 100000, condition, null, null);
		return this.excelService.toExcel(analysis, "预计订货分析报表.xlsx");
	}
	
}
